$(function() {
	
	/**
	 * Thing对象
	 * @author keluo <pycorvn@yeah.net>
	 * @since 2012-12-5 17:18:35
	 */
	var Thing = {
		
		init : function() {
			var _this = this;
			if($('#SC_middle .thing').length == 0) {
				// $.get()...
			} else {
				$('#SC_middle .thing').each(function() {
					_this.attach($(this).attr('data-thing-id'));
				});
			}
		},
		
		/**
		 * @param int divide 分隔点thing_id
		 * @param int number 获取thing条数
		 * @param bool later true则获取thing_id大于divide的thing，否则获取小于divide的thing
		 * @param function callback 回调方法名
		 * @return void
		 */
		fetchThings : function(divide, number, later, callback) {
			var _this = this;
			var later = later ? 1 : 0;
			$.get(SCABISH.host+'/thing/getThings/divide/'+divide+'/later/'+later+'/number/'+number, function(response) {
				if(SCABISH.isOk(response)) {
					var things = SCABISH.obtain(response);
					for(var i = 0; i < things.length; i++) {
						if(later) {
							$(_this.getTemplate(things[i])).hide().insertBefore($('#SC_middle .thing').first()).slideDown();
						} else {
							$(_this.getTemplate(things[i])).hide().insertAfter($('#SC_middle .thing').last()).slideDown();
						}
						
						_this.attach(things[i].thing_id);
					}
					if(typeof callback == 'function') callback(things.length);
				}
			});
		},
		
		getTemplate : function(thing) {
			var template = '\
			<div class="thing" data-thing-id="'+thing.thing_id+'" data-thing-type="'+thing.type+'">\
    			<div class="timeline" style="visibility:hidden;">'+thing.post_date+'</div>\
    			<div class="content">'+thing.text+'</div>';
			if(thing.type == 'photo') {
				template += '\
				<div class="photo">\
    				<!-- 默认显示中图 -->\
    				<div class="medium">\
	    				<img src="'+SCABISH.host+'/upload/'+thing.photos[0].thumbs[400]['path']+'" />\
	    				<span class="count">'+thing.photos.length+'p</span>\
    				</div>\
    				<ul class="thumbnail">';
				for(var i = 0; i < thing.photos.length; i++) {
					template += '\
						<li'+(i > 5 ? 'style="display:none;"' : '')+'>\
							<a class="fancybox" rel="group'+thing.thing_id+'" href="'+SCABISH.host+'/upload/'+thing.photos[i].path+'" title="'+thing.text+'" onclick="return false;">\
								<img src="'+SCABISH.host+'/upload/'+thing.photos[i].thumbs[80]['path']+'" />\
							</a>\
						</li>';
				}
				template += '\
					</ul>\
				</div>';
			} else if(thing.type == 'video') {
				template += '\
				<div class="video">\
    				<img src="'+SCABISH.host+'/upload/'+thing.video.preview_path+'" width="'+thing.video.preview_width+'" height="'+thing.video.preview_height+'" />\
    				<div class="play" data-video-url="'+thing.video.url+'" \
    					data-video-width="'+thing.video.width+'" data-video-height="'+thing.video.height+'">\
    				</div>\
    			</div>\
    			<div class="player" style="display:none;"></div>';
			} else if(thing.type == 'music') {
				template += '\
				<div class="music">\
					<img src="'+SCABISH.host+'/upload/'+thing.music.preview_path+'" width="'+thing.music.preview_width+'" height="'+thing.music.preview_height+'" />\
    				<div class="play" data-music-url="'+thing.music.url+'" \
    					data-music-width="'+thing.music.width+'" data-music-height="'+thing.music.height+'">\
    				</div>\
    			</div>\
    			<div class="player" style="display:none;"></div>';
			}
			template += '\
				<div class="opt clear">\
					<a class="edit" href="javascript:;" style="display:none;"></a>\
    				<a class="delete" href="javascript:;" style="display:none;"></a>\
    				<a class="echo" href="javascript:;"></a>\
    				<a class="share" href="javascript:;"></a>\
    				<a class="mark" href="javascript:;"></a>\
	    		</div>\
	    		<div class="echoes" style="display:none"></div>\
    		</div>';
			
			return template;
		},
		
		// 为指定thing附加事件
		attach : function(thing_id) {
			var $thing = this.getThingObj(thing_id);
			var thing_type = this.getThingType(thing_id);
			this.attachCommon(thing_id);
			switch(thing_type) {
				case 'video':
					this.attachVideo(thing_id);
				break;
				case 'music':
					this.attachMusic(thing_id);
				break;
				case 'photo':
					this.attachPhoto(thing_id);
				break;
			}
		},
		
		// 注册公共事件
		attachCommon : function(thing_id) {
			var $thing = this.getThingObj(thing_id);
			$thing.hover(function() {
				$thing.find('.timeline').css('visibility', 'visible');
				$thing.find('.opt .edit, .opt .delete').show();
			}, function(){
				$thing.find('.timeline').css('visibility', 'hidden');
				$thing.find('.opt .edit, .opt .delete').hide();
			});
			
			$thing.find('.opt .echo').click(function() {
				if($thing.find('.echoes').is(':hidden')) {
					var html = '<ul style="margin-top:10px;">\
						<li style="border-top:1px solid #eee;padding:10px;" data-echo-id="1822805">\
						<a href="/u/3001">\
							<img style="float:left;" class="avatar" width="35" height="35" alt="" src="http://i01.lw.aliimg.com/he/tz/tzhe_c7aee1b3_440_441.50x50.jpg">\
						</a>\
						<div style="float:left;margin-left:10px;">\
							<span class="remove-comment"></span>\
							<div class="content">\
								<a class="bbl-name-card" href="/u/3001" data-uid="3001">name</a>\
						幸福就是每天凌晨两点前能睡觉，宝宝不要哭闹◑▂◐\
							</div>\
							<div class="footer">\
								<span class="timestamp" timestamp="1353767445000">昨天 22:30</span>\
								<a class="reply-echo" href="javascript:;">回复</a>\
							</div>\
						</div>\
						<div style="clear:both;"></div>\
						</li>\
						<li style="border-top:1px solid #eee;padding:10px;" data-echo-id="1822805">\
						<a href="/u/3001">\
							<img style="float:left;" class="avatar" width="35" height="35" alt="" src="http://i01.lw.aliimg.com/he/tz/tzhe_c7aee1b3_440_441.50x50.jpg">\
						</a>\
						<div style="float:left;margin-left:10px;">\
							<span class="remove-comment"></span>\
							<div class="content">\
								<a class="bbl-name-card" href="/u/3001" data-uid="3001">name</a>\
						幸福就是每天凌晨两点前能睡觉，宝宝不要哭闹◑▂◐\
							</div>\
							<div class="footer">\
								<span class="timestamp" timestamp="1353767445000">昨天 22:30</span>\
								<a class="reply-echo" href="javascript:;">回复</a>\
							</div>\
						</div>\
						<div style="clear:both;"></div>\
						</li>\
						</ul>';
					$thing.find('.echoes').html(html).slideDown();
				} else {
					$thing.find('.echoes').slideUp(function() {$(this).empty();});
				}
			});
		},
		
		attachVideo : function(thing_id) {
			var $thing = this.getThingObj(thing_id);
			
			// Common(thing_id);
			var recreate = function() {
				$player = $thing.find('.play');
				return '\
				<div>\
					<embed src="'+$player.attr('data-video-url')+'"\
						type="application/x-shockwave-flash" width="'+$player.attr('data-video-width')+'"\
						height="'+$player.attr('data-video-height')+'" wmode="transparent" play="true"\
						loop="false" menu="false" allowscriptaccess="never">\
					</embed>\
				</div>';
			};
			
			$thing.find('.video .play').click(function() {
				$thing.find('.video img').click();
			});
			
			$thing.find('.video img').hover(function() {
				$(this).stop().animate({'opacity': 0.7});
			}, function() {
				$(this).stop().animate({'opacity': 1});
			}).click(function() {
				var $player = $thing.find('.player');
				if($player.is(':hidden')) {
					$(this).parent().hide();
					var html = recreate();
					html += '<div><a href="javascript:;" class="turnup"></a><a href="javascript:;" class="reload"></a></div>';
					$player.hide().html(html).fadeIn();
				} else {
					var _this = $(this);
					$player.animate({height:0}, 'normal', 'swing', function() {
						$(this).css({'height':''}).empty().hide();
						_this.parent().slideDown();
					});
				}
				
				$player.find('.turnup').die().live('click', function() {
					$thing.find('.video img').click();
				});
				
				$player.find('.reload').die().live('click', function() {
					$player.children().eq(0).fadeOut(function() {
						$(this).remove();
						$player.prepend(recreate());
					})
				});
			});
		},
		
		attachMusic : function(thing_id) {
			var $thing = this.getThingObj(thing_id);
			
			// Common(thing_id);
			
			var recreate = function() {
				$player = $thing.find('.play');
				return '\
				<div>\
					<embed src="'+$player.attr('data-music-url')+'"\
						type="application/x-shockwave-flash" width="'+$player.attr('data-music-width')+'"\
						height="'+$player.attr('data-music-height')+'" wmode="transparent" play="true"\
						loop="false" menu="false" allowscriptaccess="never">\
					</embed>\
				</div>';
			};
			
			$thing.find('.music .play').click(function() {
				$thing.find('.music img').click();
			});
			
			$thing.find('.music img').hover(
				function() {
					$(this).stop().animate({'opacity': 0.7});
				}, function() {
					$(this).stop().animate({'opacity': 1});
				}	
			).click(function() {
				var $player = $thing.find('.player');
				if($player.is(':hidden')) {
					var html = recreate();
					html += '<div><a href="javascript:;" class="turnup" title="收起"></a><a href="javascript:;" class="reload" title="重载"></a></div>';
					$player.hide().html(html).fadeIn();
				} else {
					var _this = $(this);
					$player.animate({height:0, width:0}, 'normal', 'swing', function() {
						$(this).css({'height':'', 'width':''}).empty().hide();
						_this.parent().slideDown();
					});
				}
				
				$player.find('.turnup').die().live('click', function() {
					$thing.find('.music img').click();
				});
				
				$player.find('.reload').die().live('click', function() {
					$player.children().eq(0).fadeOut(function() {
						$(this).remove();
						$player.prepend(recreate());
					})
				});
			});
		},
		
		attachPhoto : function(thing_id) {
			var $thing = this.getThingObj(thing_id);
			$thing.find('.medium img').hover(function() {
				$(this).stop().animate({'opacity': 0.7});
			}, function() {
				$(this).stop().animate({'opacity': 1});
			});
			$thing.find('.fancybox[rel="group'+thing_id+'"]').fancybox({
				openEffect	: 'none',
				closeEffect	: 'none'
			});
			$thing.find('.medium img').click(function() {
				$thing.find('.fancybox').eq(0).click();
			});
		},
		
		// 获取当前页thing_id的最大值
		getMaxThingId : function() {
			if($('#SC_middle .thing').length == 0) {
				return 0;
			}
			return $('#SC_middle .thing').first().attr('data-thing-id');
		},
		
		// 获取当前页thing_id的最小值
		getMinThingId : function() {
			if($('#SC_middle .thing').length == 0) {
				return 0;
			}
			return $('#SC_middle .thing').last().attr('data-thing-id');
		},
		
		// 获取指定thing节点对象
		getThingObj : function(thing_id) {
			return $('.thing[data-thing-id='+thing_id+']');
		},
		
		getThingType : function(thing_id) {
			return this.getThingObj(thing_id).attr('data-thing-type');
		}
	};
	
	
	// 初始化编辑器
	$('#origin').editor({
		width : 580,
		height : 40, 
		photoUploadUrl : SCABISH.host + '/photo/upload',
		sendUrl : SCABISH.host + '/thing/send',
		postSuccess : function() {
			Thing.fetchThings(Thing.getMaxThingId(), 10, true);
		}
	});
	
	// 初始化thing
	Thing.init();
	
	// 设置背景图
	$.get(SCABISH.host+'/api/background', function(response) {
		document.body.style.background = '#eee url('+response+') no-repeat fixed top';
	});
	
	// 判断是否到底
	var arrivedAtBottom = function() {
		var gap = Math.abs($(document).scrollTop() + $(window).height() - $(document).height())
		return gap <= 1;
	};
	
	$('#thing_loading').bind('mouseover', function() {
		Thing.fetchThings(Thing.getMinThingId(), 10, false, thingFinish);
	});
	
	// thing获取完成后须执行方法
	var thingFinish = function(num) {
		if(num == 0) { // 数据探底
			$('#thing_loading').attr('data-loading', 'no').attr('data-dip', '1').text('没有了').die();
		} else {
			$('#thing_loading').attr('data-loading', 'no').text('继续往下↓');
			$('#thing_loading').bind('mouseover', function() {
				Thing.fetchThings(Thing.getMinThingId(), 10, false, thingFinish);
			});
		}
	};
	
	// 注册滚动加载事件
	$(window).scroll(function(){
		if(arrivedAtBottom()) {
			if($('#thing_loading').attr('data-loading') == 'yes') return; // 正在获取thing，防止反复查询
			if($('#thing_loading').attr('data-dip') == '1') {
				return;
			}
			$('#thing_loading').attr('data-loading', 'yes').addClass('thing-loading-bg').text('loading...').die();
			Thing.fetchThings(Thing.getMinThingId(), 10, false, thingFinish);
		}
	});
});